<?php
function weixin_get_setting($appid=''){
	return get_option('weixin-robot');
}

function weixin_get_appid(){
	$setting = weixin_get_setting();
	return trim($setting['weixin_app_id']);

	if(isset($appid)) {
		return $appid;	
	}

	$appid	= '';

	
	if(is_admin()){
		$weixin_settings	= weixin_get_settings();

		if(!$weixin_settings) return '';

		if(count($weixin_settings) == 1){
			$appid	= $weixin_settings[0]['appid'];
		}else{
			global $pagenow, $plugin_page;

			if($pagenow == 'options.php'){
				$appid_str = $_POST['option_page']??'';
			}else{
				$appid_str = $plugin_page??($_REQUEST['page']??'');
			}
			
			if($appid_str && preg_match('/[-|_](wx[A-Za-z0-9]{16})/', $appid_str, $matches)){
				$appid	= ($matches[1]);
			}
		}
	}elseif(isset($_GET['appid'])){
		$appid	= $_GET['appid'];
	}else{
		global $wp;
		if (isset($wp->query_vars['appid'])) {
			$appid = $wp->query_vars['appid'];
		}else{
			$weixin_settings	= weixin_get_settings();

			if($weixin_settings && count($weixin_settings) == 1){
				$appid = $weixin_settings[0]['appid'];
			}
		}
	}
	
	return $appid;
}

function weixin_get_type($appid=''){
	$setting = weixin_get_setting($appid);
	return $setting['weixin_type']??'';
}

function weixin($appid='', $secret=''){
	$appid	= ($appid)?:weixin_get_appid();

	if(empty($appid)) {
		trigger_error('empty_appid');
		wp_die('公众号 appid 为空',	'empty_appid');
	}

	$weixin_setting	= weixin_get_setting($appid);

	if(empty($weixin_setting)){
		wp_die('公众号设置信息为空',	'请先在后台小程序设置中加入该小程序');
	}

	$secret	= ($secret)?:$weixin_setting['secret']??$weixin_setting['weixin_app_secret'];

	static $weixins;

	$weixins	= ($weixins)??array();

	if(isset($weixins[$appid])) return $weixins[$appid];

	$weixins[$appid]	= new WEIXIN($appid, $secret);

	return $weixins[$appid];
}

function weixin_exists($appid, $secret){
	$weixin			= new WEIXIN($appid, $secret);
	$access_token	= $weixin->get_access_token($force=true);
	return (is_wp_error($access_token))?false:true;
}

function weixin_get_extends($appid=''){
	$appid	= ($appid)?:weixin_get_appid();
	return get_option('weixin_'.$appid.'_extends');
}

function weixin_include_extends($admin=false){
	$weixin_extends	= weixin_get_extends();
	if(!$weixin_extends) return;

	$weixin_extend_dir 	= $admin? WEIXIN_ROBOT_PLUGIN_DIR.'extends/admin': WEIXIN_ROBOT_PLUGIN_DIR.'extends';
	foreach ($weixin_extends as $weixin_extend => $value) {
		if(!$value) continue;

		$weixin_extend_file	= $weixin_extend_dir.'/'.$weixin_extend;
		if(is_file($weixin_extend_file)){
			include($weixin_extend_file);
		}
	}
}

add_filter('wpjam_rewrite_rules', function ($rewrite_rules){
	$rewrite_rules['weixin/([^/]+)/?$']	= 'index.php?module=weixin&action=$matches[1]';
	return $rewrite_rules;
});


add_filter('wpjam_template', function($template, $module, $action){
	if($module == 'weixin'){
		if(is_weixin()){
			if(weixin_get_type() == 4){
				WEIXIN_User::oauth_request();
			}

			$openid	= WEIXIN_User::get_current_openid();

			if(is_wp_error($openid)){
				wp_die('未登录');
			}else{
				$weixin_user	= WEIXIN_User::get($openid);

				if(!$weixin_user || !$weixin_user['subscribe']){
					$weixin_user	= WEIXIN_User::get($openid, array('force'=>true));	// 由于缓存的问题，强抓一次
				}

				if($weixin_user && $weixin_user['subscribe']){
					return is_file($template)? $template : apply_filters('weixin_template', WEIXIN_ROBOT_PLUGIN_DIR.'template/user/'.$action.'.php', $action);
				}else{
					wp_die('未关注');
				}
			}
		}else{
			if($action == 'reply'){
				return WEIXIN_ROBOT_PLUGIN_DIR.'template/'.$action.'.php';
			}else{
				wp_die('请在微信中访问');
			}
		}
	}elseif($module == 'json' && $action && strpos($action, 'weixin') !== false ){
		$appid	= weixin_get_appid();

		if($action != 'get_weixin_js_api_ticket'){
			wpjam_api_validate_access_token();

			$limits	= array(
				'get_weixin_access_token'		=> 100,
				'get_weixin_js_api_ticket'		=> 1000,
				'get_weixin_user'				=> 100000,
			);
			
			$limit	= isset($limits[$action])?$limits[$action]:100;

			wpjam_api_validate_quota($action, $limit);
		}

		if(strpos($action, 'stats') !== false){
			return WEIXIN_ROBOT_PLUGIN_DIR.'/template/json/stats/'.$action.'.php';
		}else{
			if(is_weixin() && weixin_get_type() == 4){
				WEIXIN_User::oauth_request();
			}
			return WEIXIN_ROBOT_PLUGIN_DIR.'/template/json/'.$action.'.php';
		}
	}
	return $template;
}, 10, 3);


wp_cache_add_global_groups([
	'weixin_messages'
]);

